package com.group4.blockchain.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group4.blockchain.common.lang.Result;
import com.group4.blockchain.pojo.RealName;
import com.group4.blockchain.pojo.User;
import com.group4.blockchain.sdk.InvokeSDK;
import com.group4.blockchain.sdk.RegisterSDK;
import com.group4.blockchain.service.RealNameService;
import com.group4.blockchain.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
//@Api(tags = {"ContractController"},description = "调用sdk")
public class ContractController {

    @Autowired
    UserService userService;
    @Autowired
    RealNameService realNameService;

//    @Autowired
//    private RedisTemplate redisTemplate;

    private static final String ORGNAME_ORG1 = "Org1";
    private static final String ADMINNAME_ORG1 = "admin";
    private static final String CA_CERT_ORG1 = "/home/ubuntu/workspace/app/example02_java/profiles/" + ORGNAME_ORG1 + "/tls/" + "ca.org1.example.com-cert.pem";
    private static final String MSPID_ORG1 = "Org1MSP";

    @ApiOperation(value="实名认证，新注册用户")
    @RequestMapping(value = "/invokeContract/realName",method = RequestMethod.POST)
    public Result registerUser(@RequestBody RealName realName){
        //map里面有id,realName,IDNum
        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", realName.getId()));
        if (user==null)
            return Result.fail("用户不存在");
        try {
            //调用添加用户sdk
            RegisterSDK.doRegisterUser(CA_CERT_ORG1, ORGNAME_ORG1, MSPID_ORG1, ADMINNAME_ORG1,user.getUsername(), user.getPassword());

            //初始化的金额sdk
            String functionName = "InitMoney";
            String type = "submit";
            InvokeSDK.sdk(ORGNAME_ORG1, user.getUsername(), type,functionName,user.getId());

            //数据库修改
            realNameService.saveOrUpdate(realName);
            user.setIsReal(1);
            userService.saveOrUpdate(user);
            return Result.succ("实名认证成功且链上用户注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("链上用户注册失败");
        }
    }






    @ApiOperation(value="添加心愿卡",notes = "接收 String userID,  String goodName, String buyerPrice")
    @RequestMapping(value = "/addBuyerCard",method = RequestMethod.POST)
    public String addBuyerCard(@RequestBody Map<String,String> map){
        try {

            String buyerID = map.get("userID");
            System.out.println(buyerID);
            User user = userService.getOne(new QueryWrapper<User>().eq("user_id",buyerID));
            String buyerListID = UUID.randomUUID().toString().replace("-","");

            String functionName = "AddBuyerCard";
            String type = "submit";

            // 调用sdk 增加心愿卡  存入用户+其心愿单
            InvokeSDK.sdk(ORGNAME_ORG1, user.getUsername(), type,functionName,buyerID, buyerListID, map.get("goodName"), map.get("buyerPrice"));

            return JSON.toJSONString(Result.succ("添加心愿卡成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("添加心愿卡失败"));
        }
    }


    @ApiOperation(value="添加清单",notes = "传入 String userID, String goodName,String sellerPrice")
    @RequestMapping(value = "/addSellerCard",method = RequestMethod.POST)
    public String addSellerCard(@RequestBody Map<String,String> map){
        try {
            Map<String,Object> map1 = new HashMap<>();
            String sellerID = map.get("userID");
            String sellerListID = UUID.randomUUID().toString().replace("-","");

            String functionName = "AddSellerCard";
            String type = "submit";
            User user = userService.getOne(new QueryWrapper<User>().eq("user_id",sellerID));
            String userName = user.getUsername();
            //添加 并 存入商家自己的+其清单   存入公共的+其清单
            InvokeSDK.sdk(ORGNAME_ORG1, userName, type,functionName,sellerID, sellerListID, map.get("goodName"),map.get("sellerPrice"));

            return JSON.toJSONString(Result.succ("添加商品清单成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("添加商品清单失败"));
        }
    }

//@RequestParam("cardID") String cardID,@RequestParam("userName") String userName,
    @ApiOperation(value="关闭心愿卡或清单",notes = "传入cardID、userName")
    @RequestMapping(value = "/closeCard",method = RequestMethod.POST)
    public String closeCard( @RequestBody Map<String,String> map){
        try {
            //加入参数
            String cardID = map.get("cardID");
            String userName = map.get("userName");
            System.out.println(cardID);
            System.out.println(userName);
            String functionName = "Close";
            String type = "submit";
            InvokeSDK.sdk(ORGNAME_ORG1, userName, type,functionName,cardID);

            return JSON.toJSONString(Result.succ("关闭清单成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("关闭清单失败"));
        }
    }


    @ApiOperation(value="查询 某用户的所有心愿卡 或 某商家的所有清单  所有详细等信息",notes = "传入userID")
    @RequestMapping(value = "/getAllCards/{userID}",method = RequestMethod.GET)
    public String getAllList(@PathVariable("userID") String userID){
        try {
            String type = "evaluate";
            User user = userService.getOne(new QueryWrapper<User>().eq("user_id",userID));

            //查询得到其所有cardID  转arraylist
            String result = InvokeSDK.sdk(ORGNAME_ORG1, user.getUsername(), type,"QueryAny",userID+"allCards");
            List<String> cardIDs = JSONObject.parseObject(result, List.class);

            List<String> res = new ArrayList<>();

            //查询 card 的详细信息
            for(String cardID: cardIDs){
                //只显示状态可交易的card
                String cardAllDetail = InvokeSDK.sdk(ORGNAME_ORG1, user.getUsername(), type,"QueryAny",cardID);
                if (JSON.parseObject(cardAllDetail,Map.class).get("listState").equals("1"))
                    res.add(cardAllDetail);
            }

            return JSON.toJSONString(Result.succ(res));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("查询失败"));
        }
    }


    @ApiOperation(value="查询 符合某一心愿卡的所有清单的 所有详细信息",notes = "传入一个buyerCardID，心愿卡ID")
    @RequestMapping(value = "/getMatchSellerCard",method = RequestMethod.POST)
    public String getMatchSellerList(@RequestBody Map<String,String> map){
        try {
            String buyerCardID = map.get("buyerCardID");
            String userName = map.get("userName");
            if (buyerCardID==null||userName==null)
                return JSON.toJSONString(Result.fail("buyerCardID或userName不存在"));
            //先获取得到所有的清单ID
            String allSellerListID= InvokeSDK.sdk(ORGNAME_ORG1, userName, "evaluate","QueryAny","allSellerCards");
            List<String> allSellerCardIDs = JSONObject.parseObject(allSellerListID, List.class);

            //遍历匹配
            for (String sellerCardID:allSellerCardIDs) {
                InvokeSDK.sdk(ORGNAME_ORG1, userName, "submit","MatchSellerCards",buyerCardID,sellerCardID);
            }

            //得到 最符合条件的产品
            String matchSellerCardIDsString = InvokeSDK.sdk(ORGNAME_ORG1, userName, "evaluate","MatchBestSellerCard",buyerCardID);
            System.out.println(matchSellerCardIDsString);
            List<String> matchSellerCardIDs = JSONObject.parseObject(matchSellerCardIDsString, ArrayList.class);
            //最符合条件的产品的详细信息
            List<Object> res = new ArrayList<>();
            for (String matchSellerCardID :matchSellerCardIDs) {
                res.add(InvokeSDK.sdk(ORGNAME_ORG1, userName , "evaluate","QueryAny",matchSellerCardID));
            }
            return JSON.toJSONString(Result.succ(res));

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("查询失败"));
        }
    }


    @ApiOperation(value="查询余额",notes = "传入userID")
    @RequestMapping(value = "/queryMoney/{userID}",method = RequestMethod.GET)
    public String queryMoney(@PathVariable("userID") String userID){
        try {
            User user = userService.getOne(new QueryWrapper<User>().eq("user_id",userID));
            String userName = user.getUsername();
            String functionName = "QueryAny";
            String type = "evaluate";
//            String userName = InvokeSDK.getUserName();
            String result = InvokeSDK.sdk(ORGNAME_ORG1, userName, type,functionName,userID+"Money");

            return JSON.toJSONString(Result.succ(result));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("查询失败"));
        }
    }

    @ApiOperation(value="充值 ",notes = "传入userID,changeValue")
    @RequestMapping(value = "/recharge",method = RequestMethod.POST)
    public String recharge(@RequestBody Map<String,String> map){
        try {
            String userID = map.get("userID");
            String changeValue = map.get("changeValue");
            if (userID==null||changeValue==null)
                return JSON.toJSONString(Result.fail("userID或changeValue不存在"));
            String type = "submit";
            User user = userService.getOne(new QueryWrapper<User>().eq("user_id",userID));
            String userName = user.getUsername();
            String result = InvokeSDK.sdk(ORGNAME_ORG1, userName, type,"Recharge",userID,changeValue);

            return JSON.toJSONString(Result.succ("充值成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("充值失败"));
        }
    }


    @ApiOperation(value="交易 ",notes = "传入userName,buyerCardID,sellerCardID")
    @RequestMapping(value = "/trans",method = RequestMethod.POST)
    public String trans(@RequestBody Map<String,String> map){
        try {
            String buyerCardID = map.get("buyerCardID");
            String sellerCardID = map.get("sellerCardID");
            String userName = map.get("userName");
            if (buyerCardID==null||sellerCardID==null||userName==null)
                return JSON.toJSONString(Result.fail("buyerCardID或sellerCardID或userName不存在"));
            String type = "submit";
            String result = InvokeSDK.sdk(ORGNAME_ORG1, userName, type,"DoTrans",buyerCardID,sellerCardID);

            return JSON.toJSONString(Result.succ("交易成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("交易失败"));
        }
    }

    @ApiOperation(value="查询交易订单等详细信息",notes = "传入userName")
    @RequestMapping(value = "/queryTransDetail",method = RequestMethod.GET)
    public String queryTransDetail(@RequestParam("userName") String userName){
        try {
            String type = "evaluate";
            String allTransIDsStr = InvokeSDK.sdk(ORGNAME_ORG1, userName, type,"QueryAny","allTransIDs");
            List<String> allTransIDs = JSONObject.parseObject(allTransIDsStr, List.class);
            ArrayList<String> res = new ArrayList<>();
            for (String allTransID:allTransIDs) {
                String details = InvokeSDK.sdk(ORGNAME_ORG1, userName, type,"QueryAny",allTransID);
                res.add(details);
            }

            return JSON.toJSONString(Result.succ(res));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("查询失败"));
        }
    }

    @ApiOperation(value="平台查询收益")
    @RequestMapping(value = "/queryPlatformProfit",method = RequestMethod.GET)
    public String queryPlatformProfit(@RequestParam("userName") String userName){
        try {
            String functionName = "QueryAny";
            String type = "evaluate";
            String result = InvokeSDK.sdk(ORGNAME_ORG1, userName, type,functionName,"platformMoney");

            return JSON.toJSONString(Result.succ(result));
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(Result.fail("查询失败"));
        }
    }



//    /**
//     * seller
//     */
//
//
//
//    //添加清单
//    @RequestMapping(value = "/doInitsellerList",method = RequestMethod.POST)
//    public String doInitsellerList(@RequestBody Map<String,String> map){
//        try {
//            //加入参数
////            String SellerID,  String SellerListID,  String goodID, String goodName,String SellerPrice
////            String userID = InvokeSDK.getUserName();
//            Map<String,Object> map1 = new HashMap<>();
//            String SellerID = map.get("UserID");
//            String SellerListID = UUID.randomUUID().toString().replace("-","");
//            String goodID = UUID.randomUUID().toString().replace("-","");
//            String functionName = "InitsellerList";
//            String type = "submit";
//            String userName = InvokeSDK.getUserName();
//            String result = InvokeSDK.sdk(ORGNAME_ORG1, userName, type,functionName,SellerID, SellerListID, goodID, map.get("goodName"),map.get("SellerPrice"));
//
//            map1.put("SellerID",SellerID);
//            map1.put("SellerListID",SellerListID);
//            map1.put("goodID",goodID);
//            map1.put("result",result);
////            return map;
//
//            return JSON.toJSONString(Result.succ(map));
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JSON.toJSONString(Result.fail("添加商品清单失败"));
//        }
//    }
    //







    //不需要的
    //    private static final String ADMINPWD_ORG1 = "adminpw";
//    private static final String USERNAME_ORG1 = "group4";
//    private static final String USERPWD_ORG1 = "blockchaingroup4";

    //初始化注册管理员和用户
    //@RequestMapping(value = "/invokeContract/init",method = RequestMethod.GET)
//    public static Result enrollAdmin(){
//        try {
//            //调用注册管理sdk
//            RegisterSDK.doEnroll(CA_CERT_ORG1, ORGNAME_ORG1, MSPID_ORG1, ADMINNAME_ORG1, ADMINPWD_ORG1);
//            //调用添加用户sdk
//            RegisterSDK.doRegisterUser(CA_CERT_ORG1, ORGNAME_ORG1, MSPID_ORG1, ADMINNAME_ORG1, USERNAME_ORG1, USERPWD_ORG1);
//            //调用初始化方法
//            //InvokeSDK.doInit(ORGNAME_ORG1,USERNAME_ORG1,RandomID.getUUID());
//            return Result.succ("初始化成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail("初始化失败");
//        }
//    }

//    @RequestMapping(value = "/test",method = RequestMethod.GET)
//    public Result test(){
//        try {
//            return Result.succ("初始化成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.fail("初始化失败");
//        }
//        }


    //    //查询某一心愿卡 的名称、价格、状态、找到符合可交易的清单数量、符合可交易的清单id
//    @RequestMapping(value = "/doQueryBuyerList/{BuyerListID}",method = RequestMethod.GET)
//    public String doQueryBuyerList(@PathVariable("BuyerListID") String BuyerListID){
//        try {
//            String functionName = "QueryBuyerList";
//            String type = "evaluate";
//            String [] findKey = {"goodName","BuyerPrice","ListState","orderNum","orderIDs"};
//            String userName = InvokeSDK.getUserName();
//            HashMap<String,String> res = new HashMap<>();
//            for (String findkey: findKey){
//                String result = InvokeSDK.sdk(ORGNAME_ORG1, userName , type,functionName,BuyerListID,findkey);
//                res.put(findkey,result);
//            }
//            return JSON.toJSONString(Result.succ(res));
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JSON.toJSONString(Result.fail("获取心愿卡细节失败"));
//        }
//    }


    //            map1.put("sellerID",sellerID);
//            map1.put("sellerListID",sellerListID);
//            map1.put("goodID",goodID);
//            map1.put("result",result);
//            return map;


    //            Map<String,Object> map1 = new HashMap<>();
//            map1.put("BuyerID",BuyerID);
//            map1.put("BuyerListID",BuyerListID);
//            map1.put("result",result);

}
